<template>
  <div class="document-previewer">
    <!-- 上传区域 -->
    <div class="upload-section">
      <div class="upload-area" @click="triggerUpload">
        <div class="upload-placeholder">
          <i class="fas fa-cloud-upload-alt"></i>
          <p>点击上传文档 (PDF或Word)</p>
          <p class="file-types">支持格式: .pdf, .doc, .docx</p>
        </div>
        <input
            type="file"
            ref="fileInput"
            @change="handleFileUpload"
            accept=".pdf,.doc,.docx"
            style="display: none;"
        >
      </div>
      <div v-if="fileName" class="file-info">
        <p><i class="fas fa-file"></i> {{ fileName }}</p>
        <button @click="downloadFile" class="download-btn">
          <i class="fas fa-download"></i> 下载
        </button>
      </div>
    </div>

    <!-- 预览区域和信息面板 -->
    <div class="preview-section">
      <!-- 左侧预览区域 -->
      <div class="preview-container">
        <div v-if="isLoading" class="loading-overlay">
          <div class="spinner"></div>
          <p>{{ isLoadingMessage }}</p>
        </div>

        <div v-if="error" class="error-message">
          <i class="fas fa-exclamation-triangle"></i>
          <p>{{ errorMessage }}</p>
          <button @click="clearError" class="retry-btn">重试</button>
        </div>

        <!-- PDF预览 -->
        <div v-if="fileType === 'pdf' && pdfUrl" class="pdf-preview">
          <iframe :src="pdfUrl" class="pdf-iframe"></iframe>
        </div>

        <!-- Word预览 -->
        <div v-if="fileType === 'word' && htmlContent" class="word-preview-container">
          <div class="word-preview" v-html="htmlContent"></div>
        </div>

        <!-- 空状态 -->
        <div v-if="!fileType && !isLoading && !error" class="empty-state">
          <i class="fas fa-file-alt"></i>
          <p>上传文档以预览内容</p>
        </div>
      </div>

      <!-- 右侧信息面板 -->
      <div class="info-panel">
        <div class="panel-header">
          <i class="fas fa-info-circle"></i>
          <h3>文档信息</h3>
        </div>

        <div class="info-content">
          <div class="info-item">
            <span class="info-label">文档名称:</span>
            <span class="info-value">{{ fileName || '未上传' }}</span>
          </div>

          <div class="info-item">
            <span class="info-label">文档类型:</span>
            <span class="info-value">{{ fileType ? fileType.toUpperCase() : '未上传' }}</span>
          </div>

          <div class="info-item">
            <span class="info-label">上传时间:</span>
            <span class="info-value">{{ uploadTime || '--' }}</span>
          </div>

          <div class="info-item">
            <span class="info-label">文件大小:</span>
            <span class="info-value">{{ fileSize || '--' }}</span>
          </div>

          <!-- 仅Word文档显示以下信息 -->
          <template v-if="fileType === 'word'">
            <div class="info-item">
              <span class="info-label">总字数:</span>
              <span class="info-value">{{ wordCount || '--' }}</span>
            </div>

            <div class="info-item">
              <span class="info-label">关键词:</span>
              <div class="keywords-container">
                <span v-for="(keyword, index) in keywords" :key="index" class="keyword-tag">
                  {{ keyword }}
                </span>
              </div>
            </div>

            <div class="info-item">
              <span class="info-label">文档摘要:</span>
              <div class="summary-content">
                {{ documentSummary || '暂无摘要' }}
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import mammoth from 'mammoth';
import DOMPurify from 'dompurify';

// 响应式变量
const fileInput = ref(null);
const fileName = ref('');
const fileType = ref('');
const fileData = ref(null);
const pdfUrl = ref('');
const htmlContent = ref('');
const isLoading = ref(false);
const isLoadingMessage = ref('加载文档中...');
const error = ref(false);
const errorMessage = ref('');
const uploadTime = ref('');
const fileSize = ref('');
const wordCount = ref(0);
const keywords = ref([]);
const documentSummary = ref('');
const birdFeatures = ref([]);


// 触发文件上传
const triggerUpload = () => {
  fileInput.value.click();
};

// 清除状态
const clearState = () => {
  fileType.value = '';
  pdfUrl.value = '';
  htmlContent.value = '';
  error.value = false;
  errorMessage.value = '';
  uploadTime.value = '';
  fileSize.value = '';
  wordCount.value = 0;
  keywords.value = [];
  documentSummary.value = '';
  isLoadingMessage.value = '加载文档中...';
};

// 错误处理
const handleError = (message, err) => {
  console.error(message, err);
  error.value = true;
  errorMessage.value = `${message}: ${err.message || '未知错误'}`;
};

// 将文件读取为ArrayBuffer
const readFileAsArrayBuffer = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => resolve(e.target.result);
    reader.onerror = reject;
    reader.readAsArrayBuffer(file);
  });
};


// 鸟类相关词汇库
const birdKeywords = [
  '鸟类', '鸟', '雀', '鹰', '鸮', '鸵鸟', '企鹅', '鸽子', '鹦鹉', '乌鸦',
  '麻雀', '喜鹊', '啄木鸟', '猫头鹰', '翠鸟', '白鹭', '丹顶鹤', '天鹅',
  '海鸥', '孔雀', '黄鹂', '画眉', '百灵鸟', '燕子', '大雁', '布谷鸟',
  '火烈鸟', '隼', '鹳', '鹈鹕', '鸬鹚', '蜂鸟', '知更鸟', '红隼', '白头鹎',
  '羽毛', '翅膀', '喙', '爪子', '鸟巢', '迁徙', '孵化', '鸟蛋', '鸣叫',
  '栖息地', '候鸟', '留鸟', '水鸟', '猛禽', '捕食', '飞翔', '鸟类保护区'
];

// 鸟类特征词汇
const birdFeatureWords = [
  '羽毛', '翅膀', '飞翔', '喙', '爪子', '鸟巢', '迁徙', '孵化', '鸟蛋',
  '鸣叫', '捕食', '栖息', '筑巢', '羽毛颜色', '飞行姿态', '觅食', '繁殖'
];



const analyzeTextContent = (text) => {
  // 计算字数
  wordCount.value = text.trim().split(/\s+/).length;

  // 转换为小写以便匹配
  const lowerText = text.toLowerCase();

  // 提取鸟类关键词
  const foundKeywords = [];
  birdKeywords.forEach(keyword => {
    const lowerKeyword = keyword.toLowerCase();
    if (lowerText.includes(lowerKeyword)) {
      foundKeywords.push(keyword);
    }
  });

  // 按在文本中出现的顺序排序
  keywords.value = foundKeywords.sort((a, b) => {
    return lowerText.indexOf(a.toLowerCase()) - lowerText.indexOf(b.toLowerCase());
  });

  // 提取鸟类特征
  const foundFeatures = [];
  birdFeatureWords.forEach(feature => {
    const lowerFeature = feature.toLowerCase();
    if (lowerText.includes(lowerFeature)) {
      foundFeatures.push(feature);
    }
  });
  birdFeatures.value = foundFeatures;

  // 生成摘要（取前120个字符）
  documentSummary.value = text.substring(0, 120) + (text.length > 120 ? '...' : '');
};

// 预览PDF文档
const previewPdf = async (file) => {
  try {
    // 读取文件为 ArrayBuffer
    const arrayBuffer = await readFileAsArrayBuffer(file);

    // 创建Blob URL用于预览
    const blob = new Blob([arrayBuffer], { type: 'application/pdf' });
    if (pdfUrl.value) URL.revokeObjectURL(pdfUrl.value);
    pdfUrl.value = URL.createObjectURL(blob);

    return true;
  } catch (err) {
    throw err;
  }
};

// 预览Word文档
const previewWord = async (file) => {
  try {
    // 读取文件为 ArrayBuffer
    const arrayBuffer = await readFileAsArrayBuffer(file);

    // 转换Word为HTML
    const result = await mammoth.convertToHtml({ arrayBuffer });

    // 清理HTML防止XSS攻击
    const cleanHtml = DOMPurify.sanitize(result.value);
    htmlContent.value = cleanHtml;

    // 提取文本内容进行分析
    const textContent = extractTextFromHtml(cleanHtml);
    analyzeTextContent(textContent);

    return true;
  } catch (err) {
    throw err;
  }
};

// 从HTML中提取纯文本
const extractTextFromHtml = (html) => {
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = html;
  return tempDiv.textContent || tempDiv.innerText || '';
};

// 处理文件上传
const handleFileUpload = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 重置状态
  clearState();
  isLoading.value = true;
  fileName.value = file.name;

  // 设置上传时间和文件大小
  uploadTime.value = new Date().toLocaleString();
  fileSize.value = formatFileSize(file.size);

  try {
    // 确定文件类型
    const extension = file.name.toLowerCase().split('.').pop();
    if (extension === 'pdf') {
      fileType.value = 'pdf';
      await previewPdf(file);
    } else if (['doc', 'docx'].includes(extension)) {
      fileType.value = 'word';
      await previewWord(file);
    } else {
      throw new Error('不支持的文件格式');
    }

    // 保存文件数据用于下载
    fileData.value = file;
  } catch (err) {
    handleError('文档预览失败', err);
  } finally {
    isLoading.value = false;
  }
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 下载文件
const downloadFile = () => {
  if (!fileData.value) return;

  const url = URL.createObjectURL(fileData.value);
  const a = document.createElement('a');
  a.href = url;
  a.download = fileName.value;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

// 清除错误
const clearError = () => {
  error.value = false;
  errorMessage.value = '';
};
</script>

<style scoped>
.document-previewer {
  display: flex;
  flex-direction: column;
  height: 80vh;
  width: 90%;
  max-width: 1200px;
  background: #f8f9fa;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin: 20px auto;
}

.upload-section {
  padding: 20px;
  background: white;
  border-bottom: 1px solid #e9ecef;
}

.upload-area {
  height: 150px;
  border: 2px dashed #4361ee;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8f9fa;
}

.upload-area:hover {
  border-color: #3a0ca3;
  background: #f0f2f5;
}

.upload-placeholder {
  text-align: center;
  color: #6c757d;
}

.upload-placeholder i {
  font-size: 48px;
  color: #4361ee;
  margin-bottom: 10px;
}

.upload-placeholder p {
  margin: 5px 0;
  font-size: 16px;
}

.file-types {
  font-size: 14px;
  color: #868e96;
}

.file-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding: 10px;
  background: #f1f3f5;
  border-radius: 8px;
}

.file-info p {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #495057;
}

.download-btn {
  background: #4361ee;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s ease;
}

.download-btn:hover {
  background: #3a0ca3;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.preview-section {
  display: flex;
  flex: 1;
  position: relative;
  overflow: hidden;
}

.preview-container {
  flex: 1;
  position: relative;
  overflow: auto;
  padding: 15px;
  background: white;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid #f3f3f3;
  border-top: 5px solid #4361ee;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 25px;
  border-radius: 10px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  text-align: center;
  z-index: 11;
  max-width: 80%;
}

.error-message i {
  font-size: 2.5rem;
  color: #e74c3c;
  margin-bottom: 15px;
}

.error-message p {
  margin: 0 0 20px 0;
  font-size: 1.1rem;
  color: #495057;
}

.retry-btn {
  background: #4361ee;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.retry-btn:hover {
  background: #3a0ca3;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.pdf-preview {
  width: 100%;
  height: 100%;
}

.pdf-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

/* 新增容器用于限制宽度 */
.word-preview-container {
  width: 100%;
  max-width: 100%;
  overflow: auto;
  padding: 20px;
  box-sizing: border-box;
}

.word-preview {
  max-width: 800px; /* 限制最大宽度 */
  margin: 0 auto; /* 居中显示 */
  padding: 30px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  line-height: 1.6;
  color: #333;
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);

  /* 确保文本自动换行 */
  word-wrap: break-word;
  overflow-wrap: break-word;
  white-space: pre-wrap;
}

.word-preview * {
  /* 为所有子元素添加换行支持 */
  word-wrap: break-word;
  overflow-wrap: break-word;
  white-space: pre-wrap;

  /* 限制所有元素的最大宽度 */
  max-width: 100%;
}

.word-preview h1, .word-preview h2, .word-preview h3 {
  color: #2c3e50;
  margin-top: 1.5em;
  margin-bottom: 0.5em;
}

.word-preview p {
  margin-bottom: 1em;
}

.word-preview ul, .word-preview ol {
  margin-left: 20px;
  margin-bottom: 1em;
}

.word-preview table {
  border-collapse: collapse;
  margin-bottom: 1em;
  width: 100%;
  /* 确保表格内文本换行 */
  table-layout: fixed;
  word-break: break-all;
}

.word-preview table, .word-preview th, .word-preview td {
  border: 1px solid #ddd;
}

.word-preview th, .word-preview td {
  padding: 8px;
  text-align: left;
  /* 确保表格单元格内文本换行 */
  word-wrap: break-word;
}

.word-preview th {
  background-color: #f2f2f2;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #868e96;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 15px;
  color: #adb5bd;
}

.empty-state p {
  margin: 0;
  font-size: 18px;
}

/* 信息面板样式 */
.info-panel {
  width: 300px;
  background: white;
  border-left: 1px solid #e9ecef;
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.panel-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
}

.panel-header i {
  font-size: 24px;
  color: #4361ee;
}

.panel-header h3 {
  margin: 0;
  font-size: 18px;
  color: #343a40;
}

.info-content {
  flex: 1;
}

.info-item {
  margin-bottom: 15px;
}

.info-label {
  display: block;
  font-weight: 600;
  color: #495057;
  margin-bottom: 5px;
}

.info-value {
  display: block;
  color: #6c757d;
}

.keywords-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 5px;
}

.keyword-tag {
  background: #e0f7fa;
  color: #00838f;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 12px;
}

.summary-content {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 6px;
  margin-top: 5px;
  font-size: 14px;
  line-height: 1.5;
  color: #495057;
}
</style>